using System;
using System.Diagnostics;
using System.Windows.Forms;
using Microsoft.Win32;

namespace ArchiveMe.Code
{
    static class ContextMenuManager
    {
        public static void Register(
            string fileType, string shellKeyName,
            string menuText, string menuCommand)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileType) &&
                         !string.IsNullOrEmpty(shellKeyName) &&
                         !string.IsNullOrEmpty(menuText) &&
                         !string.IsNullOrEmpty(menuCommand));

            string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);

            using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(regPath))
            {
                key.SetValue(null, menuText);
            }

            using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
                string.Format(@"{0}\command", regPath)))
            {
                key.SetValue(null, menuCommand);
            }
        }

        public static void Unregister(string fileType, string shellKeyName)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileType) && !string.IsNullOrEmpty(shellKeyName));

            string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);

            Registry.ClassesRoot.DeleteSubKeyTree(regPath);
        }

        public static bool IfExists(string fileType, string shellKeyName)
        {
            try
            {
                string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);
                RegistryKey RegKey = Registry.ClassesRoot.CreateSubKey(regPath);

                if (RegKey != null)
                {
                    object obj = RegKey.GetValue("");
                    return obj != null;
                }
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error occoured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
    }
}